using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class FileDataHander
{
    private string dataDirPath = Application.persistentDataPath;
    private string dataName = "save";
    private bool datajiami = false;
    private string datajiamiMessage = "gazili";
    public FileDataHander(bool datajiami)
    {
        this.datajiami = datajiami;
    }
    public void Save(GameData data)
    {
        string savePath = dataDirPath + "/" + dataName;
        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
        string dataToStore = JsonUtility.ToJson(data);
        if (datajiami) dataToStore = DataJiaMI(dataToStore);
        using (FileStream stream = new FileStream(savePath, FileMode.Create))
        {
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.Write(dataToStore);
            }
        }
        Debug.Log(savePath);
    }
    public GameData Load()
    {
        string fullPath = dataDirPath + "/" + dataName;
        GameData loadData = null;
        if (!File.Exists(fullPath)) return null;
        string dataToload = string.Empty;
        using (FileStream stream = new FileStream(fullPath, FileMode.Open))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                dataToload = reader.ReadToEnd();
            }
        }
        if (datajiami) dataToload = DataJiaMI(dataToload);
        loadData = JsonUtility.FromJson<GameData>(dataToload);
        return loadData;
    }
    public void Delete()
    {
        string fullPath = dataDirPath + "/" + dataName;
        if (File.Exists(fullPath))
        {
            File.Delete(fullPath);
        }
    }
    private string DataJiaMI(string data)
    {
        string modifierdata = string.Empty;
        for (int i = 0; i < data.Length; ++i)
        {
            modifierdata += (char)(data[i] ^ datajiamiMessage[i % datajiamiMessage.Length]);
        }
        return modifierdata;
    }
}